package jeye.utils;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import jeye.Defaults;

import org.apache.log4j.Logger;


public class FileUtils {
	
	private static final Logger LOG = Logger.getLogger(FileUtils.class);

	public static String createEventFramesDirectory(String eventUUID) {
		String dirName = Defaults.OUTPUT_DIR + eventUUID;
		File dir = new File(dirName);
		
		dir.mkdir();
			
		return dirName;
	}
	
	public static List<File> getEventFrames(String eventUUID) {
		File dir = new File(Defaults.OUTPUT_DIR + eventUUID);

		return Arrays.asList(dir.listFiles());
	}
	
	public static void saveFrame(BufferedImage image, String directory, String filename) {
		try {
			File outputFile = new File(directory + "//" + filename + "." + Defaults.OUTPUT_FORMAT);
			ImageUtils.write(image, Defaults.OUTPUT_FORMAT, outputFile, Defaults.CAPTURE_QUALITY);
		} catch (IOException e) {
			LOG.error("Error during saving image to disk", e);
		}
	}
	
	public static byte[] getBytesFromFile(File file) {
		FileInputStream fis = null;

		try {
			fis = new FileInputStream(file);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			byte[] buffer = new byte[256];
			int count;
			
			while((count = fis.read(buffer)) > 0) {
				baos.write(buffer, 0, count);
			}
			
			return baos.toByteArray();
			
		}catch(Exception e) {
			LOG.error("Error during getting bytes from file", e);
		} finally {
			if(fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					LOG.error("Cannot close stream", e);
				}
			}
		}
		
		return null;
	}
	
	public static boolean deleteEventDir(String eventUUID) {
		return deleteDir(new File(Defaults.OUTPUT_DIR + eventUUID));
	}
	
	private static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            
            for (int i=0; i<children.length; i++) {
                File file = new File(dir, children[i]);
				boolean success = deleteDir(file);
				
                if (!success) {
                	LOG.warn("Failed to delete file: " + file.getAbsolutePath());
                    return false;
                }
            }
        }
        return dir.delete();
    }

}
